<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$response = [
    'success' => false,
    'message' => '',
    'uploadedCount' => 0
];

try {
    // 检查是否有文件上传
    if (empty($_FILES['images'])) {
        throw new Exception('没有选择文件');
    }

    // 图片目录路径 (根据实际情况修改)
    $uploadDir = '/var/www/html/picture/';
    
    // 创建目录如果不存在
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $uploadedCount = 0;
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    
    foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
        // 检查上传错误
        if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
            continue;
        }
        
        // 检查文件类型
        $fileType = mime_content_type($tmpName);
        if (!in_array($fileType, $allowedTypes)) {
            continue;
        }
        
        // 生成唯一文件名
        $originalName = basename($_FILES['images']['name'][$key]);
        $extension = pathinfo($originalName, PATHINFO_EXTENSION);
        $newFilename = uniqid() . '.' . strtolower($extension);
        $destination = $uploadDir . $newFilename;
        
        // 移动文件
        if (move_uploaded_file($tmpName, $destination)) {
            $uploadedCount++;
            
            // 设置文件权限
            chmod($destination, 0644);
        }
    }
    
    if ($uploadedCount === 0) {
        throw new Exception('没有文件被成功上传');
    }
    
    $response['success'] = true;
    $response['uploadedCount'] = $uploadedCount;
    $response['message'] = "成功上传 {$uploadedCount} 张图片";
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>